﻿using System;
using System.Collections.Generic;
using KSP.IO;
using UnityEngine;
using System.Linq;

namespace KSPCapability
{
	public class CapabilityPersistance
	{
		private static CapabilityPersistance _instance;

		private const string RecordsFileName = "records";
		private List<Capability> _capabilities = new List<Capability>();

		static CapabilityPersistance()
		{
			_instance = new CapabilityPersistance();
		}
		
		public static CapabilityPersistance Instance
		{
			get { return _instance; }
		}

		public CapabilityPersistance()
		{
			if (!KSP.IO.File.Exists<CapabilityPersistance>(RecordsFileName)) Save();

			_capabilities = (List<Capability>) IOUtils.DeserializeFromBinary(File.ReadAllBytes<CapabilityPersistance>(RecordsFileName));
		}

		private void Save()
		{
			KSP.IO.File.WriteAllBytes<CapabilityPersistance>(KSP.IO.IOUtils.SerializeToBinary(_capabilities), RecordsFileName);
		}

		public List<Capability> GetCapabilities()
		{
			return _capabilities.ToList();
		}

		public void Record(Capability c)
		{
			_capabilities.Add(c);
			Save();
		}
	}

	public static class Extensions
	{
		public static bool PercentTolerance(this int percent, double x, double y)
		{
			return (x*(100 + percent)/100.0 > y && x*(100 - percent)/100.0 < y);
		}
	}
}